package com.technology.education.ext

import android.app.Activity
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI
import android.provider.MediaStore.MediaColumns.IS_PENDING
import android.provider.Settings
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.navigation.NavDirections
import androidx.navigation.NavOptions
import androidx.navigation.Navigation
import androidx.navigation.fragment.NavHostFragment
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import com.angcyo.dsladapter.DslAdapter
import com.angcyo.dsladapter.DslAdapterItem
import com.angcyo.dsladapter.findItemByTag
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target
import com.huantansheng.easyphotos.EasyPhotos
import com.huantansheng.easyphotos.callback.SelectCallback
import com.huantansheng.easyphotos.models.album.entity.Photo
import com.jeremyliao.liveeventbus.LiveEventBus
import com.technology.education.MyApplication
import com.technology.education.MyApplication.Companion.context
import com.technology.education.R
import com.technology.education.base.AppViewModel
import com.technology.education.data.AppData
import com.technology.education.data.SpKeys
import com.technology.education.dslitem.ItemColumnTitleEdit
import com.technology.education.dslitem.ItemColumnTitleText
import com.technology.education.dslitem.ItemSingleEdit
import com.technology.education.dslitem.ItemSingleText
import com.technology.education.ui.common.login.ActivityLogin
import com.technology.education.ui.common.pay.PayActivity
import com.technology.education.ui.common.preview_photo.PreviewPhotoActivity
import com.technology.education.ui.common.role_selector.RoleSelectorActivity
import com.technology.education.ui.common.web.WebActivity
import com.technology.education.utils.LogUtil
import com.technology.education.utils.ScreenUtil
import com.technology.education.utils.rom.*
import com.technology.education.widget.GlideEngine
import com.tencent.bugly.Bugly.applicationContext
import com.tencent.imsdk.v2.V2TIMManager
import me.hgj.jetpackmvvm.ext.lifecycle.KtxActivityManger
import me.hgj.jetpackmvvm.util.startActivity
import java.io.*
import java.text.SimpleDateFormat
import java.util.*


fun Fragment.checkLogin(): Boolean {
    if (!isLogin()) {
        startActivity(RoleSelectorActivity::class)
    }
    return isLogin()
}

/**
 * 提示dialog
 */
fun Activity.notifyDialog(notify: String, confirm: () -> Unit) {
    AlertDialog.Builder(this).setTitle("提示")
        .setMessage(notify)
        .setNegativeButton(
            "确定"
        ) { p0, _ ->
            p0?.dismiss()
            confirm.invoke()
        }
        .setPositiveButton("取消") { p0, _ ->
            p0?.dismiss()
        }.create()
        .show()
}

fun Fragment.notifyDialog(
    title: String? = "提示",
    notify: String,
    cancel: () -> Unit? = {},
    confirm: () -> Unit
) {
    AlertDialog.Builder(requireContext()).setTitle(title)
        .setMessage(notify)
        .setNegativeButton(
            "确定"
        ) { p0, _ ->
            p0?.dismiss()
            confirm.invoke()
        }
        .setPositiveButton("取消") { p0, _ ->
            p0?.dismiss()
            cancel.invoke()
        }.create()
        .show()
}

fun Fragment.customDialog(
    title: String? = "提示",
    notify: String,
    confirmStr: String = "确定",
    cancelStr: String = "取消",
    cancel: () -> Unit? = {},
    confirm: () -> Unit
) {
    MaterialDialog(requireContext()).cornerRadius(8f)
        .customView(R.layout.dialog_cancel_wait).show {
            getCustomView().findViewById<TextView>(R.id.dialog_content)?.text = notify
            getCustomView().findViewById<TextView>(R.id.dialog_title)?.text = title
            getCustomView().findViewById<TextView>(R.id.dialog_confirm)?.apply {
                text = confirmStr
                setOnClickListener {
                    confirm.invoke()
                    dismiss()
                }
            }
            getCustomView().findViewById<TextView>(R.id.dialog_cancel)?.apply {
                text = cancelStr
                setOnClickListener {
                    cancel.invoke()
                    dismiss()
                }
            }
        }
}

/**
 * 退出登录,跳转到选择角色页面
 */
fun Fragment.logout() {
    AppData.TOKEN = ""
    saveData(SpKeys.TOKEN, "")
    saveData(SpKeys.IS_LOGIN, false)
    V2TIMManager.getInstance().logout(null)
    KtxActivityManger.finishActivity(requireActivity())
    startActivity(RoleSelectorActivity::class)
}

/**
 * 登录过期,重新登录
 */
fun Activity.reLogin() {
    AppData.TOKEN = ""
    saveData(SpKeys.TOKEN, "")
    saveData(SpKeys.IS_LOGIN, false)
    KtxActivityManger.finishAllActivity()
    startActivity(Intent(this, ActivityLogin::class.java))
}

/**
 * 根据页码更新数据
 */
fun DslAdapter.setPageItems(list: List<DslAdapterItem>, page: Int) {
    if (page == 1) {
        resetItem(list)
    } else {
        appendItems(list)
    }
}

/**
 * 加载更多数据
 */
fun DslAdapter.appendItems(list: List<DslAdapterItem>) {
    dataItems.addAll(list)
    _updateAdapterItems()
    updateItemDepend()
}

/**
 * 获取Text 类型item中的数据
 */
fun DslAdapter.getItemText(tag: String): String? {
    var data: String? = ""
    findItemByTag(tag)?.let {
        when (it) {
            is ItemColumnTitleText -> {
                data = it.content
            }
            is ItemSingleText -> {
                data = it.title
            }
            is ItemSingleEdit -> {
                data = it.title
            }
            is ItemColumnTitleEdit -> {
                data = it.content
            }
        }
    }
    return data
}

/**
 * 设置 Text 类型Item 中的数据
 */

fun DslAdapter.setItemText(tag: String, content: String?) {
    findItemByTag(tag)?.let {
        when (it) {
            is ItemSingleText -> {
                it.title = content
            }
            is ItemColumnTitleText -> {
                it.content = content
            }
            is ItemSingleEdit -> {
                it.title = content
            }
            is ItemColumnTitleEdit -> {
                it.content = content
            }
        }
        it.updateAdapterItem()
    }
}

/**
 * 申请悬浮窗权限
 */
fun applyAlertPermission() {

}


/**
 * 判断悬浮窗权限
 */
fun checkAlertPermission(): Boolean {
    //6.0 版本之后由于 google 增加了对悬浮窗权限的管理，所以方式就统一了
    if (Build.VERSION.SDK_INT < 23) {
        when {
            RomUtils.checkIsMiuiRom() -> {
                return MiuiUtils.checkFloatWindowPermission(context)
            }
            RomUtils.checkIsMeizuRom() -> {
                return MeizuUtils.checkFloatWindowPermission(context)
            }
            RomUtils.checkIsHuaweiRom() -> {
                return HuaweiUtils.checkFloatWindowPermission(context)
            }
            RomUtils.checkIs360Rom() -> {
                return QikuUtils.checkFloatWindowPermission(context)
            }
            RomUtils.checkIsOppoRom() -> {
                return OppoUtils.checkFloatWindowPermission(context)
            }
        }
    }
    return if (RomUtils.checkIsMeizuRom()) {
        MeizuUtils.checkFloatWindowPermission(context)
    } else {
        var result = true
        if (Build.VERSION.SDK_INT >= 23) {
            try {
                val clazz: Class<*> = Settings::class.java
                val canDrawOverlays = clazz.getDeclaredMethod(
                    "canDrawOverlays",
                    Context::class.java
                )
                result = canDrawOverlays.invoke(null, context) as Boolean
            } catch (e: Exception) {
            }
        }
        result
    }

}


/**
 * 不能发送 empty 数据
 */
fun postEventBus(key: String, value: Any) {
    LiveEventBus.get<Any>(key).post(value)
}

fun postEventBus(key: String, value: Any, delay: Long) {
    LiveEventBus.get<Any>(key).postDelay(value, delay)
}

fun AppCompatActivity.observe(key: String, callBack: (value: Any) -> Unit = {}) {
    LiveEventBus.get<Any>(key).observe(this, Observer {
        callBack.invoke(it)
    })
}

fun <T> AppCompatActivity.observe(key: String, type: Class<T>, callBack: (T) -> Unit) {
    LiveEventBus.get(key, type).observe(this, Observer {
        callBack.invoke(it)
    })
}

fun Fragment.observe(key: String, callBack: (value: Any) -> Unit = {}) {
    LiveEventBus.get<Any>(key).observe(viewLifecycleOwner, Observer {
        callBack.invoke(it)
    })
}

fun <T> Fragment.observe(key: String, type: Class<T>, callBack: (T) -> Unit) {
    LiveEventBus.get(key, type).observe(viewLifecycleOwner) {
        callBack.invoke(it)
    }
}


/**
 * 跳转到拨号页面，无需申请权限
 */
fun Context.callPhoneDial(phone: String?) {
    if (phone.isNullOrEmpty()) {
        return
    }

    try {
        val intent = Intent(Intent.ACTION_DIAL)
        val data = Uri.parse("tel:$phone")
        intent.data = data
        startActivity(intent)
    } catch (e: Exception) {

    }

}

/**
 * 跳转到拨号页面，无需申请权限
 */
fun Fragment.callPhoneDial(phone: String?) {
    phone?.let {
        val intent = Intent(Intent.ACTION_DIAL)
        val data = Uri.parse("tel:$it")
        intent.data = data
        startActivity(intent)
    }
}

/**
 * log 数据
 */
fun showLog(log: String) {
    LogUtil.instance!!.printJson(log)
}

fun toast(content: String) {
    Toast.makeText(context, content, Toast.LENGTH_SHORT).show()
}

/**
 * 当前fragment是否在栈中
 */
fun <T : Fragment> Fragment.isFragmentInStack(fragment: Class<T>): Boolean {
    childFragmentManager.fragments.let {
        it.forEach { child ->
            if (fragment.isAssignableFrom(child.javaClass)) {
                return true
            }
        }
    }
    return false
}

/**
 * 当前fragment是否在栈中
 */
fun <T : Fragment> AppCompatActivity.isFragmentInStack(fragment: Class<T>): Boolean {
    val navHostFragment = this.supportFragmentManager.fragments.first() as NavHostFragment
    navHostFragment.childFragmentManager.fragments.let {
        it.forEach { item ->
            if (fragment.isAssignableFrom(item.javaClass)) {
                return true
            }
        }
    }
    return false
}

/**
 * 当前fragment是否在栈顶
 */
fun <T : Fragment> AppCompatActivity.isFragmentInTop(fragment: Class<T>): Boolean {
    val navHostFragment = this.supportFragmentManager.fragments.first() as NavHostFragment
    navHostFragment.childFragmentManager.fragments.let {
        if (fragment.isAssignableFrom(it.last().javaClass)) {
            return true
        }
    }
    return false
}

/**
 * 当前fragment是否在栈顶
 */
fun <T : Fragment> Fragment.isFragmentInTop(fragment: Class<T>): Boolean {
    val navHostFragment = activity!!.supportFragmentManager.fragments.first() as NavHostFragment
    navHostFragment.childFragmentManager.fragments.let {
        if (fragment.isAssignableFrom(it.last().javaClass)) {
            return true
        }
    }
    return false
}

/**
 * 获取当前栈中的fragment总数
 */
fun AppCompatActivity.fragmentInStackSize(): Int {
    val navHostFragment = this.supportFragmentManager.fragments.first() as NavHostFragment
    return navHostFragment.childFragmentManager.fragments.size
}

fun getCachePath(): String {
    return if (Environment.MEDIA_MOUNTED == Environment.getExternalStorageState() || !Environment.isExternalStorageRemovable()) {
        context.externalCacheDir!!.absolutePath
    } else {
        context.cacheDir.absolutePath
    }
}

/**
 * 发现如果快速点击会报找不到目标id的错误，可能是因为首次点击已经进入节点，二次点击之后该节点已经不存在了所以导致报错，
 * 如果为每个view添加防止重复点击逻辑太麻烦，所以这里直接捕获该异常
 */
fun navigation(view: View, actionId: Int) {
    try {
        Navigation.findNavController(view).navigate(actionId)
    } catch (e: IllegalArgumentException) {
        showLog("navigation------$e")
    }
}

/**
 * 使用 deeplink 进行跳转
 */
fun navigation(view: View, deepLink: Uri, options: NavOptions? = null) {
    try {
        Navigation.findNavController(view).navigate(
            deepLink, options ?: NavOptions.Builder().setEnterAnim(R.anim.slide_in_right)
                .setExitAnim(R.anim.slide_out_left)
                .setPopExitAnim(R.anim.slide_out_right)
                .setPopEnterAnim(R.anim.slide_in_left).build()
        )
    } catch (e: IllegalArgumentException) {
        LogUtil.instance!!.log(e.toString())
    }
}

/**
 * 使用 deeplink 进行跳转
 */
fun navigation(view: View, deepLink: String, options: NavOptions? = null) {
    try {
        Navigation.findNavController(view).navigate(
            Uri.parse(deepLink), options ?: NavOptions.Builder().setEnterAnim(R.anim.slide_in_right)
                .setExitAnim(R.anim.slide_out_left)
                .setPopExitAnim(R.anim.slide_out_right)
                .setPopEnterAnim(R.anim.slide_in_left).build()
        )
    } catch (e: IllegalArgumentException) {
        LogUtil.instance!!.log(e.toString())
    }
}

fun navigation(view: View, action: NavDirections) {
    try {
        Navigation.findNavController(view).navigate(action)
    } catch (e: IllegalArgumentException) {
        showLog(e.toString())
    }
}

fun Fragment.back() {
    Navigation.findNavController(requireView()).navigateUp()
}

fun navigation(view: View, actionId: Int, args: Bundle) {
    try {
        Navigation.findNavController(view).navigate(actionId, args)
    } catch (e: IllegalArgumentException) {

    }
}

/**
 * 退到指定的fragment
 */
fun popTo(view: View, desId: Int, args: Boolean = false) {
    try {
        Navigation.findNavController(view).popBackStack(desId, args)
    } catch (e: IllegalArgumentException) {
        showLog(e.toString())
    }
}

fun AppCompatActivity.getAppViewModel(): AppViewModel {
    (MyApplication.getApp() as MyApplication).let {
        return it.getAppViewModelProvider().get(AppViewModel::class.java)
    }
}

fun Fragment.getAppViewModel(): AppViewModel {
    (MyApplication.getApp() as MyApplication).let {
        return it.getAppViewModelProvider().get(AppViewModel::class.java)
    }
}

fun getAppViewModel(): AppViewModel {
    (MyApplication.getApp() as MyApplication).let {
        return it.getAppViewModelProvider().get(AppViewModel::class.java)
    }
}

/**
 * 加载头像
 */
fun header(url: String?, img: ImageView) {
    loadImage(url, img, errImg = R.drawable.round_gray)
}

/**
 * 加载普通图片
 */
fun loadImage(
    url: String?,
    img: ImageView,
    errImg: Int = 0,
    withCrossFade: Boolean = true
) {
    val glideBuilder = Glide.with(context)
        .load(url ?: "").placeholder(R.drawable.round_gray)
    if (withCrossFade) {
        glideBuilder.transition(DrawableTransitionOptions.withCrossFade(200))
    }
    if (errImg > 0) {
        glideBuilder.error(errImg)
    }
    glideBuilder.into(img)
}


/**
 * 加载普通资源图片
 */
fun loadImage(
    resId: Int,
    img: ImageView,
    withCrossFade: Boolean = true
) {
    val glideBuilder = Glide.with(context)
        .load(resId)
    if (withCrossFade) {
        glideBuilder.transition(DrawableTransitionOptions.withCrossFade(500))
    }
    glideBuilder.into(img)
}

/**
 * 加载视频截图
 */
fun loadImageVideo(
    url: String,
    img: ImageView,
    withCrossFade: Boolean = true
) {
    val glideBuilder = Glide.with(context)
        .setDefaultRequestOptions(
            RequestOptions()
                .frame(2000000)
                .centerCrop()
        )
        .load(url)
    if (withCrossFade) {
        glideBuilder.transition(DrawableTransitionOptions.withCrossFade(500))
    }
    glideBuilder.into(img)
}


/**
 * 获取drawable 中 图片资源
 */
fun getResId(resId: Int): Drawable? {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        context.getDrawable(resId)
    } else {
        context.resources.getDrawable(resId)
    }
}

fun getColor(resId: Int): Int {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        context.getColor(resId)
    } else {
        context.resources.getColor(resId)
    }
}

fun Activity.getColors(resId: Int): Int {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        this.getColor(resId)
    } else {
        this.resources.getColor(resId)
    }
}

fun Fragment.getColor(resId: Int): Int {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        this.requireContext().getColor(resId)
    } else {
        this.requireContext().resources.getColor(resId)
    }
}

/**
 * 获取进程号对应的进程名
 *
 * @param pid 进程号
 * @return 进程名
 */
fun getProcessName(pid: Int): String? {
    var reader: BufferedReader? = null
    try {
        reader = BufferedReader(FileReader("/proc/$pid/cmdline"))
        var processName = reader.readLine()
        if (!TextUtils.isEmpty(processName)) {
            processName = processName.trim { it <= ' ' }
        }
        return processName
    } catch (throwable: Throwable) {
        throwable.printStackTrace()
    } finally {
        try {
            reader?.close()
        } catch (exception: IOException) {
            exception.printStackTrace()
        }

    }
    return null
}

fun getVersionName(): String {
    var verName = ""
    try {
        verName = context.packageManager.getPackageInfo(context.packageName, 0).versionName
    } catch (e: PackageManager.NameNotFoundException) {
        e.printStackTrace();
    }
    return verName

}

fun getScreenHeight(): Int {
    return ScreenUtil.getScreenHeight(context)
}

fun getScreenWide(): Int {
    return ScreenUtil.getScreenWidth(context)
}


/**
 * 生成随机文件名：当前年月日时分秒+五位随机数
 *
 * @return
 */
fun getRandomFileName(): String {
    val simpleDateFormat: SimpleDateFormat
    simpleDateFormat = SimpleDateFormat("yyyyMMddHHmmss")
    val date = Date()
    val str = simpleDateFormat.format(date)
    val random = Random()
    return str // 当前时间
}

/**
 * 选择照片
 */
fun Fragment.selectPhoto(
    count: Int = 1,
    showCamera: Boolean = true,
    selectedList: ArrayList<Photo>,
    callBack: (ArrayList<Photo>) -> Unit
) {
    EasyPhotos.createAlbum(this, showCamera, false, GlideEngine.getInstance())
        .setFileProviderAuthority("com.technology.education.fileprovider")
        .setPuzzleMenu(false)
        .setSelectedPhotos(selectedList)
        .setCount(count)
        .start(object : SelectCallback() {
            override fun onResult(photos: ArrayList<Photo>?, isOriginal: Boolean) {
                if (photos.isNullOrEmpty()) {
                    toast("请选择照片")
                } else {
                    callBack.invoke(photos)
                }
            }

            override fun onCancel() {

            }
        })
}

/**
 * 选择照片
 */
fun Activity.selectPhoto(
    count: Int = 1,
    showCamera: Boolean = true,
    selectedList: ArrayList<Photo>,
    callBack: (ArrayList<Photo>) -> Unit
) {
    EasyPhotos.createAlbum(this, showCamera, false, GlideEngine.getInstance())
        .setFileProviderAuthority("com.technology.education.fileprovider")
        .setPuzzleMenu(false)
        .setSelectedPhotos(selectedList)
        .setCount(count)
        .start(object : SelectCallback() {
            override fun onResult(photos: ArrayList<Photo>?, isOriginal: Boolean) {
                if (photos.isNullOrEmpty()) {
                    toast("请选择照片")
                } else {
                    callBack.invoke(photos)
                }
            }

            override fun onCancel() {

            }
        })
}

/**
 * 跳转到支付页main
 * @param money 需要支付的金额
 * @param orderId 订单id
 */
fun Fragment.toPayActivity(money: String, orderId: String, type: Int) {
    startActivity(
        PayActivity::class,
        Pair("orderId", orderId),
        Pair("money", money),
        Pair("type", type)
    )
}

/**
 * 预览图片
 * @param pos 当前图片的位置,从0开始
 * @param photos 图片列表,需要进行序列化
 * @param canDel 能否删除
 */
fun Fragment.toPreviewPhoto(pos: Int = 0, photos: ArrayList<String>, canDel: Boolean = false) {
    startActivity(
        PreviewPhotoActivity::class,
        Pair("pos", pos),
        Pair("photos", photos),
        Pair("canDel", canDel)
    )
}

/**
 * 跳转到web页面
 * @param title 图片列表,需要进行序列化
 * @param url 能否删除
 */
fun Fragment.toWebActivity(title: String, url: String) {
    startActivity(
        WebActivity::class,
        Pair("title", title),
        Pair("url", url)
    )
}

/**
 * 下载图片
 */
fun downImage(url: String) {
    showLog("downImage--$url")
    Glide.with(context)
        .downloadOnly()
        .load(url)
        .addListener(object : RequestListener<File> {
            override fun onLoadFailed(
                e: GlideException?,
                model: Any?,
                target: Target<File>?,
                isFirstResource: Boolean
            ): Boolean {
                toast("图片下载失败")
                return false
            }

            override fun onResourceReady(
                resource: File?,
                model: Any?,
                target: Target<File>?,
                dataSource: DataSource?,
                isFirstResource: Boolean
            ): Boolean {
                showLog("onResourceReady---${resource?.absolutePath}")
                if (Build.VERSION.SDK_INT >= 29) {
                    saveFile(context, resource)
                } else {
                    saveImageToGallery(context, resource?.absolutePath ?: "")
                }
                return false
            }

        }).preload()
}

fun saveFile(context: Context, file: File?): Uri? {
    val folderName = "Pictures"
    val extension = ".jpg"
    val mimeType = "image"
    val values = ContentValues()
    values.put(MediaStore.Files.FileColumns.MIME_TYPE, mimeType)
    values.put(MediaStore.Files.FileColumns.DATE_ADDED, System.currentTimeMillis() / 1000)
    values.put(MediaStore.Files.FileColumns.DATE_TAKEN, System.currentTimeMillis())
    values.put(MediaStore.Files.FileColumns.RELATIVE_PATH, folderName)
    values.put(MediaStore.Files.FileColumns.IS_PENDING, true)
    values.put(
        MediaStore.Files.FileColumns.DISPLAY_NAME,
        "img_" + System.currentTimeMillis() + extension
    )
    val uri: Uri? =
        context.contentResolver.insert(EXTERNAL_CONTENT_URI, values)

    uri?.apply {
        runCatching {
            saveFileToStream(
                context.contentResolver.openInputStream(Uri.fromFile(file))!!,
                context.contentResolver.openOutputStream(uri)!!
            )
            values.put(MediaStore.Video.Media.IS_PENDING, false)
            context.contentResolver.update(this, values, null, null)
            toast("图片以保存到相册")
            return this
        }.getOrElse {
            return null
        }
    }
    toast("图片以保存到相册")
    return uri
}

fun saveFileToStream(input: InputStream, outputStream: OutputStream) {
    input.use { input ->
        runCatching {
            outputStream.use { output ->
                val buffer = ByteArray(4 * 1024) // or other buffer size
                var read: Int
                while (input.read(buffer).also { read = it } != -1) {
                    output.write(buffer, 0, read)
                }
                output.flush()
            }
        }
    }
}


//保存图片到相册
fun saveImageToGallery(context: Context, path: String) {
    val file = File(path)

//其次把文件插入到系统图库
    try {
        val filename = path.substring(path.lastIndexOf('/') + 1)
        MediaStore.Images.Media.insertImage(
            context.contentResolver,
            file.absolutePath, filename, null
        )

    } catch (e: FileNotFoundException) {
        e.printStackTrace()
    }

// 通知图库更新
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        MediaScannerConnection.scanFile(
            context, arrayOf(file.absolutePath), null
        ) { path, uri ->
            val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
            mediaScanIntent.data = uri
            context.sendBroadcast(mediaScanIntent)
        }
    } else {
        val relationDir = file.parent
        val file1 = File(relationDir)
        context.sendBroadcast(Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.fromFile(file1.absoluteFile)))
    }
    toast("图片以保存到相册")
}


